<!--
 * @author wangpeizhi
   荣誉管理 - 新增荣誉
 -->
<template>
  <div class="app-container proof-increate">
    <div class="proof-increate-title">新建/编辑荣誉信息</div>
    <div v-loading="loading" class="proof-increate-form">
      <el-form ref="baseform" :model="baseform" :rules="baserules" label-width="150px" class="baseform">
        <el-form-item label="荣誉类型" required prop="honorType">
          <el-col :span="24">
            <el-form-item prop="honorType">
              <el-select v-model="baseform.honorType" placeholder="请选择" @change="changeHonorType(1)">
                <el-option v-for="item in dict.RYFL" :key="item.id" :label="item.dictName" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item :label="labelList.honorType" required prop="classifyId">
          <el-col :span="24">
            <el-form-item prop="classifyId">
              <el-cascader
                ref="classify"
                v-model="baseform.classifyId"
                style="width: 100%"
                clearable
                :props="createClassifyProps"
                :options="secondClassfiy"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item :label="labelList.name" prop="honorName">
          <el-input v-model="baseform.honorName" placeholder="请输入名称" maxlength="30" />
        </el-form-item>
        <el-form-item v-if="labelList.honorType !== '证书分类'" label="是否使用模板" prop="isTemplate">
          <el-radio-group v-model="baseform.isTemplate">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="baseform.isTemplate === 0">
          <el-form-item :label="labelList.successIMg" prop="honorImg" required>
            <!-- <image-upload
      :key="uploadFile.imagecropperKey"
      v-model="baseform.honorImg"
      :preview-id="uploadFile.viewId"
      :forever="true"
      :width="1024"
      :view="uploadFile.view"
      :height="680"
      :no-circle="true"
      :no-rotate="false"
      lang-type="zh"
    /> -->
            <el-button style="margin-left: 10px" @click="handleCreate(1)">上传图片</el-button>
            <el-image v-if="baseform.honorImg != ''" :src="uploadFile.view + baseform.honorImg" />
          </el-form-item>
          <el-form-item
            v-if="baseform.honorType === 'RYFL_CJ' || baseform.honorType === 'RYFL_XZ'"
            :label="labelList.failIMG"
            prop="honorImgFail"
            required
          >
            <el-button style="margin-left: 10px" @click="handleCreate(2)">上传图片</el-button>
            <el-image v-if="baseform.honorImgFail != ''" :src="uploadFile.view + baseform.honorImgFail" />
          </el-form-item>
        </template>
        <template v-if="baseform.isTemplate === 1 && labelList.honorType !== '证书分类'">
          <el-form-item label="请选择模板" prop="templateId">
            <el-select v-model="baseform.templateId" placeholder="请选择" @change="getTemplateId">
              <el-option v-for="item in options" :key="item.id" :label="item.templateName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="模板文字" prop="templateText">
            <el-input v-model.trim="baseform.templateText" type="text" placeholder="请输入模板文字" />
          </el-form-item>
          <el-form-item v-for="(item, index) in ctImg" :key="index" :label="item.name">
            <el-image class="ctImg" :src="item.contentOos" :preview-src-list="[item.contentOos]" />
          </el-form-item>
        </template>
        <el-form-item v-if="baseform.honorType === 'RYFL_ZS'" label="背景颜色">
          <div class="block">
            <el-color-picker v-model="baseform.backColor" />
          </div>
        </el-form-item>
        <el-form-item v-if="labelList.honorType == '证书分类'" :label="labelList.Level" prop="honorLevel">
          <el-col :span="24">
            <el-form-item prop="honorLevel">
              <el-select v-model="baseform.honorLevel" placeholder="请选择等级">
                <el-option label="无" value="无" />
                <el-option label="企业级" value="企业级" />
                <el-option label="省市级" value="省市级" />
                <el-option label="国家级" value="国家级" />
                <el-option
                  v-for="item in dict.certGrade"
                  :key="item.id"
                  :label="item.dictName"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item v-if="labelList.honorType == '证书分类'" :label="labelList.Grade" prop="honorGrade">
          <el-col :span="24">
            <el-form-item prop="honorGrade">
              <el-select v-model="baseform.honorGrade" placeholder="请选择级别">
                <el-option label="无" value="无" />
                <el-option label="初级" value="初级" />
                <el-option label="中级" value="中级" />
                <el-option label="高级" value="高级" />
                <el-option
                  v-for="item in dict.certLevel"
                  :key="item.id"
                  :label="item.dictName"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item v-if="baseform.honorType === 'RYFL_ZS'" :label="labelList.Explain" prop="honorExplain">
          <el-input
            v-model.trim="baseform.honorExplain"
            :autosize="{ minRows: 2, maxRows: 6 }"
            type="textarea"
            :placeholder="labelList.placeholderExplain"
          />
        </el-form-item>
        <el-form-item v-if="baseform.honorType != 'RYFL_ZS'" :label="labelList.remark" prop="remark">
          <el-input
            v-model.trim="baseform.remark"
            :autosize="{ minRows: 2, maxRows: 6 }"
            type="textarea"
            :placeholder="labelList.placeholderremark"
            maxlength="300"
          />
        </el-form-item>
        <el-form-item label="设置有效期" prop="isValidity">
          <el-radio-group v-model="baseform.isValidity">
            <el-radio label="ISVALIDITY01">是</el-radio>
            <el-radio label="ISVALIDITY02">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="baseform.isValidity == 'ISVALIDITY01'" label="有效期开始时间" prop="validityStart">
          <el-date-picker
            v-model="baseform.validityStart"
            type="datetime"
            placeholder="选择开始日期"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item v-if="baseform.isValidity == 'ISVALIDITY01'" label="有效期结束时间" prop="validityEnd">
          <el-date-picker
            v-model="baseform.validityEnd"
            type="datetime"
            placeholder="选择结束日期"
            default-time="23:59:59"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item v-if="baseform.honorType ==='RYFL_ZS'" label="用户昵称" prop="originalId">
          <el-input v-model="baseform.originalId" type="text" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item v-if="baseform.honorType ==='RYFL_ZS'" label="证书前缀" prop="prefixs">
          <el-input v-model="baseform.prefixs" type="text" placeholder="请输入证书前缀" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="baseform.sort" placeholder="请输入排序号（值越大，越靠前）" maxlength="5" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="baseform.status">
            <el-radio label="ZT01">启用</el-radio>
            <el-radio label="ZT02">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="text-align: center" label-width="0">
          <el-button style="padding: 10px 30px" @click="onCancel">取 消</el-button>
          <el-button type="primary" @click="state === 'create' ? createProof('baseform') : updateProof('baseform')">确
            定
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <Upload
      v-if="uploadFile.showUpload"
      ref="upload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = false"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        : 只能上传：图片文件
      </div>
    </Upload>
  </div>
</template>
<script>
import { number, specialText } from '@/utils/validate'
import Upload from '../components/upload'
import {getToken} from '@/utils/auth'
import {addproof, getDictByCode, proofdetail, updateProof, getSysClassfiy, getTem} from '../api/index'

export default {
  name: 'AddProof',
  components: {Upload},
  data() {
    return {
      type: '1',
      state: '',
      loading: false,
      view: '/API-DOCUMENT/document/file/download?id=',
      labelList: {
        honorType: '',
        name: '',
        successIMg: '',
        failIMG: '',
        Level: '',
        Grade: '',
        Explain: '',
        placeholderExplain: '',
        remark: '',
        placeholderremark: ''
      },
      baseform: {
        honorName: '',
        honorImg: '', // 模板
        honorImgFail: '',
        honorType: 'RYFL_CJ', // 分类
        honorLevel: '',
        honorGrade: '',
        validityStart: '',
        validityEnd: '',
        status: 'ZT01',
        isValidity: 'ISVALIDITY02',
        honorExplain: '', // 内容
        remark: '', // 说明
        sort: '',
        backColor: '',
        classifyId: [],
        isTemplate: 1,
        templateId: '',
        templateText: '',
        originalId: '',
        prefixs: ''
      },
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: false,
        accept: '',
        fileType: '',
        fileIndex: 0,
        imgType: 1
      },
      uploadaction: '/API-DOCUMENT/document/file/insert',
      uploadHeaders: {ttsxauthtoken: getToken()},
      baserules: {
        honorName: [{required: true, message: '请填写名称', trigger: 'blur'}, { validator: specialText, trigger: 'blur' }],
        honorImg: [{required: true, message: '请上传图片', trigger: 'blur'}],
        honorImgFail: [{required: true, message: '请上传图片', trigger: 'blur'}],
        honorType: [{required: true, message: '请选择分类', trigger: 'blur'}],
        sort: [{required: true, message: '请输入数字', trigger: 'blur'}, { validator: number, trigger: 'blur' }],
        status: [{required: true, message: '请选择', trigger: 'blur'}],
        isValidity: [{required: true, message: '请选择', trigger: 'blur'}],
        validityStart: [{required: true, message: '请选择', trigger: 'blur'}],
        validityEnd: [{required: true, message: '请选择', trigger: 'blur'}],
        classifyId: [{required: true, message: '请选择', trigger: 'blur'}],
        isTemplate: [{required: true, message: '请选择', trigger: 'blur'}],
        templateId: [{required: true, message: '请选择', trigger: 'blur'}]
      },
      classifyTopOptions: [],
      ctImg: [],
      dict: {
        RYFL: []
      },
      createClassifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      secondClassfiy: [],
      classifyArr: [], //  级联选择器选中的数组
      options: []
    }
  },
  watch: {
    'baseform.honorType': {
      handler(newVal, oldVal) {
        if (newVal === 'RYFL_CJ') {
          this.labelList.honorType = '成就分类'
          this.labelList.name = '成就名称'
          this.labelList.successIMg = '成就达标模板'
          this.labelList.failIMG = '成就未达标模板'
          // this.labelList.Level = '成就等级'
          // this.labelList.Grade = '成就级别'
          this.labelList.Explain = '成就内容'
          this.labelList.placeholderExplain = '请输入成就内容'
          this.labelList.remark = '成就说明'
          this.labelList.placeholderremark = '请输入成就说明'
        } else if (newVal === 'RYFL_XZ') {
          this.labelList.honorType = '勋章分类'
          this.labelList.name = '勋章名称'
          this.labelList.successIMg = '勋章达标模板'
          this.labelList.failIMG = '勋章未达标模板'
          // this.labelList.Level = '勋章等级'
          // this.labelList.Grade = '勋章级别'
          this.labelList.Explain = '勋章内容'
          this.labelList.placeholderExplain = '请输入勋章内容'
          this.labelList.remark = '勋章说明'
          this.labelList.placeholderremark = '请输入勋章说明'
        } else if (newVal === 'RYFL_ZS') {
          this.labelList.honorType = '证书分类'
          this.labelList.name = '证书名称'
          this.labelList.successIMg = '证书模板'
          this.labelList.Level = '证书等级'
          this.labelList.Grade = '证书级别'
          this.labelList.Explain = '证书内容'
          this.labelList.placeholderExplain = '请输入证书内容'
          this.labelList.remark = '证书说明'
          this.labelList.placeholderremark = '请输入证书说明'
        } else {
          this.labelList.honorType = '称号分类'
          this.labelList.name = '称号名称'
          // this.labelList.Level = '称号等级'
          // this.labelList.Grade = '称号级别'
          this.labelList.successIMg = '称号达标模板'
          this.labelList.Explain = '称号内容'
          this.labelList.placeholderExplain = '请输入称号内容'
          this.labelList.remark = '称号说明'
          this.labelList.placeholderremark = '请输入称号说明'
        }
      },
      immediate: true,
      deep: true
    },
    'baseform.isTemplate': {
      handler(val) {
        if (val === 1) {
          this.getTems()
        }
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    getTemplateId(event) {
      this.ctImg = []
      this.baseform.honorImgFail = ''
      this.baseform.honorImg = ''
      const type = this.options.find((a) => a.id == event)
      this.ctImg = JSON.parse(type.templateContent)
      this.baseform.honorImgFail = this.ctImg.length > 1 ? this.ctImg[1].content : ''
      this.baseform.honorImg = this.ctImg.length > 0 ? this.ctImg[0].content : ''
    },
    getTems() {
      return new Promise((reslove, reject) => {
        this.baseform.honorImgFail = ''
        this.baseform.honorImg = ''
        this.options = []
        if (this.baseform.honorType === 'RYFL_CJ') {
          var RYTYPE = 'MBK_RYCJ'
        } else if (this.baseform.honorType === 'RYFL_RUCH') {
          var RYTYPE = 'MBK_RYCH'
        } else if (this.baseform.honorType === 'RYFL_XZ') {
          var RYTYPE = 'MBK_RYXZ'
        } else {
          this.options = []
          return
        }
        getTem({templateBaseType: RYTYPE, status: 'ZT01'})
          .then((res) => {
            this.options = res.data.data
            reslove()
          })
          .catch(() => {
            reject()
          })
      })
    },
    uploadSuccess(id, files, data) {
      if (id && this.uploadFile.imgType === 1) {
        this.baseform.honorImg = id
      } else if (id && this.uploadFile.imgType === 2) {
        this.baseform.honorImgFail = id
      }
      this.uploadFile.showUpload = false
    },
    handleCreate(id) {
      this.uploadFile.showUpload = true
      this.uploadFile.imgType = id
    },
    init() {
      for (const key in this.dict) {
        this.getDict(key)
      }
      this.state = this.$route.query.type === 'c' ? 'create' : this.$route.query.type === 'u' ? 'update' : ''
      if (this.state === 'update') {
        this.getDetail()
      }
    },
    /**
     * 获取类型
     */
    getQuery(obj) {
      var query = {
        type: this.type
      }
      return new Promise((resolve, reject) => {
        queryproof(query)
          .then((response) => {
            this.classifyTopOptions = response.data.data
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取字典
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
            if (this.state === 'create' && code === 'RYFL' && this.dict[code].length > 0) {
              this.baseform.honorType = this.dict[code][0].dictValue
              this.changeHonorType(1)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 一级分类改变时触发
    changeHonorType(a) {
      if (a == 1) {
        this.baseform.templateId = ''
        this.baseform.templateText = ''
        this.ctImg = []
        this.baseform.isTemplate = 0

        this.getTems()
      }
      getSysClassfiy({classifyType: this.baseform.honorType})
        .then(({data}) => {
          if (data.data && data.data.length > 0) {
            this.loop(data.data, 'ZT02')
            this.secondClassfiy = data.data
          } else {
            this.secondClassfiy = []
          }
        })
        .catch(() => {
        })
    },
    // 获取级联选择器选中的最后的一级id
    changeCascader(value) {
      this.baseform.classifyId = value[value.length - 1]
    },
    getDetail() {
      return new Promise((resolve, reject) => {
        proofdetail({id: this.$route.query.id})
          .then((response) => {
            this.baseform = Object.assign({}, {...response.data.data}) // copy obj

            if (response.data.data.classifyIds) {
              const idsArr = response.data.data.classifyIds.split(',') || []
              this.baseform.classifyId = idsArr
            } else {
              this.baseform.classifyId = [response.data.data.classifyId]
            }

            this.baseform.isTemplate = this.baseform.isTemplate ? 1 : 0
            if (this.baseform.honorType !== 'RYFL_ZS' && this.baseform.templateId) {
              this.getTems().then(() => {
                this.getTemplateId(this.baseform.templateId)
              })
            }

            this.changeHonorType()

            this.classifyArr.push(this.baseform.classifyId)

            this.baseform.startTime = response.data.data.validityStart
            this.baseform.endTime = response.data.data.validityEnd
            // this.uploadFile.viewId = response.data.data.honorImg;
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 从一个多维数据组删除一个指定key的值
    loop(data, key) {
      data.forEach((item, index) => {
        if (item.status === key) {
          data.splice(index, 1)
        }
        if (item.children.length > 0) {
          this.loop(item.children, key)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      if (res.data) {
        this.baseform.honorImg = res.data[0].id
      }
    },
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message.error('图片大小不能超过 1MB!')
      }
      return isLt1M
    },
    onCancel() {
      this.$router.back()
    },
    createProof() {
      this.$refs['baseform'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          const params = {
            ...this.baseform
          }
          params['classifyId'] =
              this.baseform.classifyId.length > 0
                ? this.baseform.classifyId[this.baseform.classifyId.length - 1]
                : ''
          return new Promise((resolve, reject) => {
            addproof(params)
              .then(() => {
                loading.close()
                this.$message({
                  message: '创建成功！',
                  type: 'success'
                })
                this.$router.back()
              })
              .catch((error) => {
                reject(error)
                loading.close()
              })
          })
        }
      })
    },
    updateProof() {
      this.$refs['baseform'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.baseform)
          tempData['classifyId'] =
              this.baseform.classifyId.length > 0
                ? this.baseform.classifyId[this.baseform.classifyId.length - 1]
                : ''
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          return new Promise((resolve, reject) => {
            updateProof(tempData)
              .then(() => {
                loading.close()
                this.dialogFormVisible = false
                this.$message({
                  message: '更新成功！',
                  type: 'success'
                })
                this.$router.back()
              })
              .catch((error) => {
                reject(error)
                loading.close()
              })
          })
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.proof-increate {
}
</style>
<style lang="scss" scoped>
.proof-increate {
  .proof-increate-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      background-color: $mainColor;
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .proof-increate-form {
    padding: 20px 0;
    background-color: #ffffff;

    .baseform {
      margin: auto 200px;

      .el-select {
        width: 96%;
      }

      .el-image {
        width: 300px;
        height: 200px;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      border: 1px dotted $mainColor;
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: $mainColor;
      text-align: center;
      cursor: pointer;
    }
  }
}
</style>
<style rel="stylesheet/scss" lang="scss">
.ctImg {
  width: 50px;
  height: 50px;
}

.proof-increate {
  .proof-increate-form {
    .avatar-uploader {
      cursor: pointer;
      position: relative;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;
      width: 300px;
      height: 180px;
      margin-bottom: 10px;

      .el-upload__tip {
        margin: 0;
        position: absolute;
        bottom: -22px;
        left: 0;
        right: 0;
        text-align: left;
        z-index: 1;
        line-height: 1.1;
        color: #999;
        font-size: 12px;
      }
    }

    .avatar-uploader:hover {
      border-color: #fe5a61;
    }

    .avatar-uploader-icon {
      font-size: 48px;
      color: #dadada;
      width: 300px;
      height: 180px;
      line-height: 180px;
      text-align: center;
    }

    .avatar {
      width: 300px;
      height: 180px;
      display: block;
    }
  }
}
</style>
